﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Web;

namespace Inspinia_MVC5.Code
{
    public class TcpConnect
    {
        public static string ip = "104.219.42.52";
        public static int port = 18345;
        public static int adjustnum = 10;
        public static TcpClient tclient;
        public static bool connected = false;
        public static Exception exception = null;
        public static int _timeout_milliseconds = 10000;
        public static string successstring = "";
        public static int successnum = 0;
        public int ConnectTcp(string data)
        {
            string[] remotedata = data.Split('$');
            int t = remotedata.Length;
            if (t > adjustnum) { return -4; }
            Thread thread = new Thread(new ThreadStart(BeginConnect));
            thread.Start();
            thread.Join(_timeout_milliseconds);
            thread.Abort();
            if (connected == true)
            {
                NetworkStream ns = tclient.GetStream();
                for (int i = 0; i < t - 1; i++){
                    byte[] senddata = System.Text.Encoding.Default.GetBytes(remotedata[i]);
                    ns.Write(senddata, 0, senddata.Length);
                    byte[] getdata = new byte[10];
                    ns.Read(getdata, 0, 1);
                    if (getdata[0] == 2) { successstring += remotedata[i].Split(',')[3] + "  "; successnum++;}
                    if (getdata[0] == 3) { return -11; }
                    if (getdata[0] == 4) { return -12; }
                    if (getdata[0] == 5) { return -13; }
                    if (getdata[0] == 6) { return -14; }
                }
                if (successstring != null &&successstring != "") { return successnum; }
                else return -3;
            }
            else if (exception != null)
            {
                return -2;
            }
            else{
                return -1;
            }
        }
        protected void BeginConnect()
        {
            try
            {
                tclient = new TcpClient(ip, port);
                // 标记成功，返回调用者
                connected = true;
            }
            catch (Exception ex)
            {
                // 标记失败
                exception = ex;
            }
        }
        public string getSuccessstring()
        {
            return successstring;
        }
        public void clean()
        {
            successstring = "";
            successnum = 0;
        }
    }
}